package com.tj.api.task;

import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.common.utils.TimeUtils;
import com.tj.bo.account.client.enums.WithDrawStatusEnum;
import com.tj.bo.account.server.dao.OrderWithdrawDao;
import com.tj.bo.account.server.entity.OrderWithdrawEntity;
import com.tj.bo.common.conf.config.RedisConfigUtil;
import com.tj.bo.common.conf.util.IpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: sm
 * Date: 2020-09-15
 * Time: 10:19
 */
@Component
public class WithdrawAutoTask {


    private static final Logger LOGGER = LoggerFactory.getLogger(WithdrawAutoTask.class);

    private static final int minits = 10;

    @Autowired
    private OrderWithdrawDao orderWithdrawDao;

    @Autowired
    private RedisConfigUtil redisDbConfigUtil;

    /**
     * 把用户提交的提现订单超过30分钟后置为处理中,每5终止查询一次
     */

    @Scheduled(cron = "0 0/5 * * * ?")
    public void setWithdrawOrdersToInProcssing() {

        String ip = IpUtils.getIp();
        String taskIp = redisDbConfigUtil.getTaskIp();
        if (!taskIp.equalsIgnoreCase(ip)) {
            LOGGER.info("============ IP不匹配不执行任务 taskIp:{}, localIp:{}  ==========", taskIp, ip);
            return;
        }

        List<OrderWithdrawEntity> orderWithdrawEntities = orderWithdrawDao.selectListByStatus(WithDrawStatusEnum.AUDIT_PROCESSING.getCode());

        if (CollectionUtils.isEmpty(orderWithdrawEntities)) {
            LOGGER.info("== 暂无要处理的提现订单==");
            return;
        }

        LOGGER.info("== 需要提现的订单数量 ==,size:{}", orderWithdrawEntities.size());
        orderWithdrawEntities.forEach(orderWithdrawEntity -> {

            long currentTime = new Date().getTime();
            long createTime = orderWithdrawEntity.getGmtCreate().getTime();
            LOGGER.info("== 需要提现的订单数量 ==,size:{}", orderWithdrawEntities.size());

            if (currentTime - createTime < 1000 * 60 * minits) {
                LOGGER.info("== 需要提现的订单数量2 ==,size:{},未到时间:{}", orderWithdrawEntities.size(), orderWithdrawEntity.getWithdrawOrderNo());
                return;
            }

            LOGGER.info("== 超时状态更新为打款中 ==,no:{}", orderWithdrawEntity.getWithdrawOrderNo());
            orderWithdrawEntity.setStatus(WithDrawStatusEnum.PAYOUT_PROCESSING.getCode())
                    .setFailureReasons("delay")
                    .setDelay(1);
            orderWithdrawDao.updateByPrimaryKey(orderWithdrawEntity);
        });


    }

}
